import os
import sys
import platform
import subprocess
from pathlib import Path


def brew_pre():
    if sys.platform == "darwin":
        # print(platform.machine())
        stdout, stderr = subprocess.Popen(["command", "-v", "brew"], stdout=subprocess.PIPE).communicate()
        # if stdout: print(stdout.decode('utf-8'))
        # if stderr: print(stderr.decode('utf-8'))
        if stdout:
            stdout, stderr = subprocess.Popen(["brew", "--prefix"], stdout=subprocess.PIPE).communicate()
            if stdout:
                brew_prefix = stdout.decode().strip()
                # print(brew_prefix)
        # print(platform.mac_ver())
    HOMEBREW_PREFIX = os.getenv("HOMEBREW_PREFIX")
    return brew_prefix or HOMEBREW_PREFIX


def down_file():
    from urllib import request
    if not os.getenv("HOMEBREW_PREFIX"):
        return
    file = os.getenv("HOMEBREW_PREFIX") + "/bin/im-select"
    if Path(file).is_file():
        os.remove(file)
    url = 'https://gitee.com/hevey88/im-select/raw/master/macOS/out/intel/im-select'
    if platform.machine() == "arm64":
        url = 'https://gitee.com/hevey88/im-select/raw/master/macOS/out/apple/im-select'
    data = request.urlopen(url).read()
    with open(file, "wb") as f:
        f.write(data)
    os.chmod(file, 0o755)


if __name__ == "__main__":
    down_file()
